package fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.imagesharing.R;
import com.example.imagesharing.addActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import adapter.StaggeredRecyclerViewAdapter;
import apimanager.RequestMessage;
import apimanager.ResponseMessage;
import entity.XiaoWaiApiBaseInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment implements RequestMessage, ResponseMessage {


    private static final String TAG = "MainActivity";
    private static final int NUM_COLUMNS = 2;
    private static final int INIT_IMAGE_NUM = 20;
    private static final int ADD_IMAGE_NUM = 5;
    private static final String REQUEST_MODE = "POST";
    //    protected FragmentActivity rmActivity;
    StaggeredRecyclerViewAdapter staggeredRecyclerViewAdapter;
    StaggeredGridLayoutManager staggeredGridLayoutManager;
    RecyclerView recyclerView;

    private ArrayList<String> mImageUrls = new ArrayList<>(100);
    private ArrayList<String> mNames = new ArrayList<>(100);

    SmartRefreshLayout smartRefreshLayout;
    public static HomeFragment fragment = new HomeFragment();

    private HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance() {
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_home, container, false);
        staggeredRecyclerViewAdapter = new StaggeredRecyclerViewAdapter(getActivity());
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(NUM_COLUMNS, LinearLayoutManager.VERTICAL);
        recyclerView = v.findViewById(R.id.recyclerView);
        initImageBitmaps();
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        recyclerView.setAdapter(staggeredRecyclerViewAdapter);
        smartRefreshLayout = v.findViewById(R.id.refresh_parent);
        //悬浮按钮 监听
        FloatingActionButton fab = v.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "here is a snackbar", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                Intent intent = new Intent(getActivity(), addActivity.class);
                startActivity(intent);
            }
        });

        //下拉刷新
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时，执行这段
                Log.i(TAG, "onRefresh: 执行了下拉刷新");
                initImageBitmaps();
                smartRefreshLayout.finishRefresh(1000);
            }
        });

        //上拉加载更多
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //上拉加载时，执行这段
                Log.i(TAG, "onLoadMore: 执行了上拉加载");
                for (int i = 0; i < ADD_IMAGE_NUM; i++) {
                    requestMessage();
                }
                smartRefreshLayout.finishLoadMore(1000);
            }
        });

//        TextView tv = v.findViewById(R.id.title);
//        tv.setText(title);
        return v;
    }


    private static final String[] INIT_NAME = {"Havasu Falls", "Trondheim", "Portugal",
            "Rocky Mountain National Park", "Mahahual", "Frozen Lake", "White Sands Desert",
            "Austrailia", "Washington"};

    private void initImageBitmaps() {
        Log.d(TAG, "initImageBitmaps: preparing bitmaps.");

//        mImageUrls.add("https://img2.baidu.com/it/u=1384998556,3952756461&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=501");
//        mNames.add("Havasu Falls");
//
//        mImageUrls.add("https://img2.baidu.com/it/u=3906899204,1673385652&fm=253&fmt=auto&app=138&f=JPEG?w=538&h=500");
//        mNames.add("Trondheim");
//
//        mImageUrls.add("https://img1.baidu.com/it/u=2124009234,996919229&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=640");
//        mNames.add("Portugal");
//
//        mImageUrls.add("https://img0.baidu.com/it/u=1714359884,3913118052&fm=253&fmt=auto&app=138&f=JPEG?w=281&h=500");
//        mNames.add("Rocky Mountain National Park");
//
//
//        mImageUrls.add("https://img1.baidu.com/it/u=353924533,2024263419&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750");
//        mNames.add("Mahahual");
//
//        mImageUrls.add("https://img1.baidu.com/it/u=2883742547,404257916&fm=253&fmt=auto&app=138&f=JPEG?w=333&h=500");
//        mNames.add("Frozen Lake");
//
//
//        mImageUrls.add("https://img1.baidu.com/it/u=417111173,1055089806&fm=253&fmt=auto?w=400&h=400");
//        mNames.add("White Sands Desert");
//
//        mImageUrls.add("https://img1.baidu.com/it/u=1094973742,2207101179&fm=253&fmt=auto&app=138&f=JPEG?w=440&h=822");
//        mNames.add("Austrailia");
//
//        mImageUrls.add("https://img0.baidu.com/it/u=1612636850,3450588167&fm=253&fmt=auto&app=138&f=JPEG?w=160&h=160");
//        mNames.add("Washington");
        for (int i = 0; i < INIT_IMAGE_NUM; i++) {
            requestMessage();
        }
        if (staggeredRecyclerViewAdapter != null)
            staggeredRecyclerViewAdapter.refreshView();
    }


    private void addImage(String url, String imageName) {
        staggeredRecyclerViewAdapter.add(imageName, url);
    }


    public void requestMessage() {
        XiaoWaiApiBaseInfo apiBaseInfo = XiaoWaiApiBaseInfo.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        FormBody body = builder.build();
        String[] apiPath = {apiBaseInfo.getBASE_API(), apiBaseInfo.getG_API(), apiBaseInfo.getM_API()};
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(apiPath[new Random().nextInt(apiPath.length)])
                        .get()
                        .addHeader("Content-Type", "application/json")
                        .build();
                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(callback);
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    private okhttp3.Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
            Snackbar.make(getActivity().findViewById(R.id.act_home), "网络请求出错，请检查网络是否异常或稍后再试",
                    Snackbar.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
            HomeFragment.newInstance().responseMessage(call, response);
        }
    };

    @Override
    public void responseMessage(Call call, Response responseMessage) throws IOException {
//        System.out.println(responseMessage.isSuccessful());
//        HomeActivity activity=getActivity()==null?new HomeActivity(): (HomeActivity) getActivity();

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (responseMessage.code() == 200) {
                    String bodyString = responseMessage.request().url().toString();
                    System.out.println(getActivity());
                    if (responseMessage.code() != 200) {
                        Snackbar.make(getActivity().findViewById(R.id.act_home),
                                responseMessage.code() + "错误", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    addImage(bodyString, INIT_NAME[new Random().nextInt(INIT_NAME.length)]);

                } else {

                    Snackbar.make(getActivity().findViewById(R.id.act_home), responseMessage.code() + "错误",
                            Snackbar.LENGTH_SHORT)
                            .show();
//                    addImage("aa","bb");
                }

            }
        });
    }


}